package com.java;

import java.util.concurrent.*;

/**
 * @author jingjintao
 * @date 2021/10/26 - 22:46
 **/
public class MyThreadPoolDemo {
    public static void main(String[] args) {

        //获取系统中CPU核数
        System.out.println(Runtime.getRuntime().availableProcessors());
        ExecutorService executorService = new ThreadPoolExecutor(
                2,
                5,
                2L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(3),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.DiscardOldestPolicy());

        try {
            for (int i = 1; i<= 10; i++) {
                executorService.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+"\t办理业务");
                });
//                try {
//                    TimeUnit.MILLISECONDS.sleep(300);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }

    private static void initPool() {
        //        ExecutorService executorService = Executors.newFixedThreadPool(5);//1池5个工作线程
//        ExecutorService executorService = Executors.newSingleThreadExecutor();//1池1个工作线程
        ExecutorService executorService = Executors.newCachedThreadPool();//1池N个工作线程

        try {
            for (int i = 1; i<= 10; i++) {
                executorService.execute(() -> {
                    System.out.println(Thread.currentThread().getName()+"\t办理业务");
                });
                try {
                    TimeUnit.MILLISECONDS.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}
